package io.gps.datatransfer.command;

import io.gps.datatransfer.utils.ByteUtils;
import io.gps.datatransfer.utils.SysDef;
import io.gps.datatransfer.utils.Utils;
import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;

import java.io.UnsupportedEncodingException;
import java.util.Map;


public class SendMsgPack {
	private static Logger logger = Logger.getLogger(SendMsgPack.class);
	public static IoBuffer get0100(String sim,int sheng,int shi,int cpys,String cph){
		IoBuffer tempdata;
		byte[] cphbyte;
		try {
			cphbyte=cph.getBytes("GBK");
			tempdata = IoBuffer.allocate(4+32+1+cphbyte.length);
			tempdata.putUnsignedShort(sheng);
			tempdata.putUnsignedShort(shi);
			//5字节 制造商 ID
			tempdata.put(ByteUtils.getLenByte(5));
			//终端型号 20字节
			tempdata.putUnsigned(0x44);
			tempdata.putUnsigned(0x35);
			tempdata.putUnsigned(0x58);
			tempdata.put(ByteUtils.getLenByte(17));
			//终端ID 7字节
			tempdata.put(ByteUtils.getLenByte(7));
			tempdata.putUnsigned(cpys);
			tempdata.put(cphbyte);
			tempdata.flip();
			return packData(tempdata,0x0100,0,sim);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static IoBuffer get0002(String sim){
		return packData(null,0x0002,0,sim);
	}

	public static IoBuffer get0102(String sim,byte[] token){
		IoBuffer tempdata;
		tempdata = IoBuffer.allocate(token.length);
		tempdata.put(token);
		tempdata.flip();
		return packData(tempdata,0x0102,0,sim);
	}

	public static IoBuffer get8001(String sim,int ackSerial,int answerId,int result){
		IoBuffer tempdata;
		tempdata = IoBuffer.allocate(5);
		tempdata.putUnsignedShort(ackSerial);
		tempdata.putUnsignedShort(answerId);
		tempdata.putUnsigned(result);
		tempdata.flip();
		return packData(tempdata,0x8001,0,sim);
	}

	public static IoBuffer get0001(String sim,int ackSerial,int answerId,int result){
		IoBuffer tempdata;
		tempdata = IoBuffer.allocate(5);
		tempdata.putUnsignedShort(ackSerial);
		tempdata.putUnsignedShort(answerId);
		tempdata.putUnsigned(result);
		tempdata.flip();
		return packData(tempdata,0x0001,0,sim);
	}



	public static IoBuffer getSDRegAck(int ackSerial,String sim){
		IoBuffer tempdata;
		tempdata = IoBuffer.allocate(3+sim.getBytes().length);
		tempdata.putUnsignedShort(ackSerial);
		tempdata.putUnsigned(0);
		if(sim.length()>0){
			tempdata.put(sim.getBytes());
		}
		tempdata.flip();
		return packData(tempdata,0x8100,0,sim);
	}

	public static IoBuffer packData(IoBuffer iobbody,int msgid,int msgSeri,String sim){
		IoBuffer data;
		IoBuffer iob = IoBuffer.allocate(1);
		iob.setAutoExpand(true);
		iob.putUnsignedShort(msgid);
		int msgLen=0;
		if(iobbody!=null){
			msgLen=iobbody.remaining();
		}
		String bins = ByteUtils.formatBinary(Integer.toBinaryString(msgLen),16);
		iob.putShort(Short.parseShort(bins, 2));
		iob.put(ByteUtils.encodeBCD(ByteUtils.formatBinary(sim,12)));
		if(msgSeri==0){
			msgSeri=ByteUtils.getIncreaseNum();
		}
		iob.putUnsignedShort(msgSeri);
		if(iobbody!=null){
			iob.put(iobbody);
		}
		iob.flip();
		int checkCode=0;
		checkCode=ByteUtils.oldcheck(iob);
		iob.position(0);
		data = IoBuffer.allocate(10);
		data.setAutoExpand(true);
		data.put((byte)0x7e);
		byte b;
		while(iob.hasRemaining()){
			b = iob.get();
			if(b==0x7e){
				data.put((byte)0x7d);
				data.put((byte)0x02);
			}else if(b==0x7d){
				data.put((byte)0x7d);
				data.put((byte)0x01);
			}else {
				data.put(b);
			};
		}
		if(checkCode==0x7e){
			data.putUnsigned(0x7d);
			data.putUnsigned(0x02);
		}else{
			data.putUnsigned(checkCode);
		}
		data.put((byte)0x7e);
		data.shrink();  //释放无用资源
		data.flip();
		return data;
	}


	public static IoBuffer Get0100ASK(String sim,IoBuffer iob){
		try {
			UpMessage upMessage=new UpMessage(iob);
			upMessage.messageBody.getUnsignedShort();
			int sta=upMessage.messageBody.getUnsigned();
			if(sta==0){
				byte[] kouling=new byte[upMessage.msgLen-3];
				upMessage.messageBody.get(kouling);
				String token=new String(kouling,"GBK");
				logger.info(sim + " 鉴权结果 "+sta+"--"+ Utils.changeCharset(token,"GBK","utf-8"));
				return get0102(sim,kouling);
			}else if(sta==1){
				Map<String,String> carMap= SysDef.CAR_LIST.get(sim);
				if(carMap!=null&&carMap.size()>0){
					String cph=carMap.get("CPH");
					String cpys=carMap.get("CPYS");
					String kl=cph+"@"+cpys;
					return get0102(sim,kl.getBytes("GBK"));
				}else{
					logger.error("sim : "+sim+"认证失败"+sta);
				}
			}else{
				logger.error("sim : "+sim+"认证失败"+sta);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		logger.error("sim : "+sim+"认证失败{"+ByteUtils.getSouDataLog(iob)+"}");
		return null;
	}
}
